<template>
  <div class="register-container">
    <div class="title">
      <span>
        <img src="@/assets/logo2.png"/>
      </span>
      <span class="sp2"></span>
      <span class="sp3">企业端</span>
    </div>

    <div class="conpane">
      <div class="p1">注册</div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名：" prop="name">
          <el-input v-model="ruleForm.name" placeholder="输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            placeholder="输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="surePassword">
          <el-input
            v-model="ruleForm.surePassword"
            type="password"
            placeholder="确认密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input
            v-model="ruleForm.phone"
            placeholder="输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="短信验证码："
          prop="smsCode"
          style="margin-bottom: 0;"
        >
          <div class="p2">
            <span class="sp2-input">
              <el-input
                v-model="ruleForm.smsCode"
                placeholder="输入短信验证码"
                style="width: 100%"
              >
              </el-input>
            </span>
            <span class="sp1"></span>
            <span class="sp2">
              <el-link
                class="minLH "
                type="warning"
                :disabled="ruleForm.isSend"
                @click="sendCode"
              >获取验证码</el-link
              >
            </span>
          </div>
        </el-form-item>

        <el-form-item style="margin-bottom: 0.5rem;">
          <span>
            <el-checkbox v-model="ruleForm.agrement" shape="square"
            >我已阅读并同意</el-checkbox
            >
          </span>
          <span>
            <el-link class="minLH" type="warning" @click="lookAgreement"
            >《信爪搜索注册协议》</el-link
            >
          </span>
        </el-form-item>

        <el-form-item>
          <el-button
            class="sp3-btn"
            type="primary"
            @click="register"
            :loading="loading"
          >注册
          </el-button
          >
          <div class="sp4">
            <span>已有账号？</span>
            <span
            ><el-link class="minLH" type="warning" @click="login"
            >立即登入</el-link
            ></span
            >
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import {validUsername} from "@/utils/validate";
  import {trace} from "../../utils/trace";
  import {AES_CBC_encrypt} from "../../utils/aes";
  import {accountCheck, phoneCheck} from "../../api/user"
  import {hkShowErrorText} from "../../utils/tools"

  export default {
    name: "register",
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!validUsername(value)) {
          callback(new Error("Please enter the correct user name"));
        } else {
          callback();
        }
      };
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error("The password can not be less than 6 digits"));
        } else {
          callback();
        }
      };
      var isSome = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再次输入密码"));
        } else if (value !== this.ruleForm.password) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      };
      var isAccount = (rule, value, callback) => {
        //min: 5, max: 16, message: '长度在 5 到 16 个字符',
        if (value === "") {
          callback(new Error("用户名为 5 到 16 个字符"));
        } else if (value.length < 5 || value.length > 16) {
          callback(new Error("用户名为 5 到 16 个字符!"));
        } else {
          if (/[a-zA-Z]/.test(value)) {
            //必须保护英文字母
            callback();
          } else {
            callback(new Error("用户名为 5 到 16 个字符!"));
          }
        }
      };
      return {
        // name  password surePassword phone smsCode  submitForm resetForm
        //  lookAgreement register login
        loading: false,
        ruleForm: {
          name: "",
          password: "",
          surePassword: "",
          phone: "",
          smsCode: "",
          agrement: false,
          isSend: false
        },
        rules: {
          name: [
            {required: true, message: "请输入用户名", trigger: "blur"},
            {type: "text", validator: isAccount, trigger: "blur"}
          ],
          password: [
            {required: true, message: "请输入密码", trigger: "blur"},
            {min: 6, max: 16, trigger: "blur"}
          ],
          surePassword: [
            {required: true, message: "请确认密码", trigger: "blur"},
            {type: "text", validator: isSome, trigger: "blur"}
          ],
          phone: [
            {required: true, message: "请输入手机号", trigger: "blur"},
            {pattern: /^1[3-9]\d{9}$/, message: "长度在11 个数字"}
          ],
          smsCode: [
            {message: "请输入短信验证码", trigger: "blur"},
            {min: 4, max: 6, message: "长度在 4到 6 个字符", trigger: "blur"}
          ]
        }
      };
    },
    mounted: function () {

    },
    watch: {
      $route: {
        handler: function (route) {
          this.redirect = route.query && route.query.redirect;
        },
        immediate: true
      }
    },
    methods: {
      lookAgreement: function () {

        this.$router.push({path: "/agreement"});
      },
      register: async function () {

        if (this.ruleForm.name && this.ruleForm.name.length > 1) {
          let res_acc = await accountCheck({account: this.ruleForm.name});
          if (res_acc.data.exist) {
            hkShowErrorText("用户名已存在。")
            return
          }
          trace("res_acc", res_acc)
        } else {
          return
        }
        if (this.ruleForm.phone && this.ruleForm.phone.length > 1) {
          let res_pho = await phoneCheck({phone: this.ruleForm.phone})
          trace("res_pho", res_pho)
          if (res_pho.data.exist) {
            hkShowErrorText("手机号已使用。")
            return
          }
        } else {
          return
        }


        let reg = {
          phone: this.ruleForm.phone,
          code: this.ruleForm.smsCode,
          password: AES_CBC_encrypt(this.ruleForm.password),
          account: this.ruleForm.name
        };

        this.$refs.ruleForm.validate(valid => {
          trace("to-register", valid);
          if (valid) {
            this.loading = true;
            this.$store
              .dispatch("user/register", reg)
              .then(() => {

                this.$router.push({path: this.redirect || "/"});
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {

            return false;
          }
        });
      },
      login: function () {

        this.$router.push({path: "/login"});
      },
      submitForm: function () {

      },
      resetForm: function () {

      },
      sendCode: function () {
        //发送短信验证码


        let reg = /^1[345789]\d{9}$/;
        if (!reg.test(this.ruleForm.phone)) {
          new Error("请输入正确的11位手机号");
          return;
        } else {
          // this.ruleForm.isSend=true;
          this.$store
            .dispatch("user/smsCode", {phone: this.ruleForm.phone})
            .then(data => {
              trace("handleLogin", data);
              this.ruleForm.smsCode = data.code;

              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        }
      },

      showPwd() {
        if (this.passwordType === "password") {
          this.passwordType = "";
        } else {
          this.passwordType = "password";
        }
        this.$nextTick(() => {
          this.$refs.password.focus();
        });
      },
      psLogin() {

        this.$router.push({path: "/login"});
      },
      handleLogin() {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.loading = true;
            this.$store
              .dispatch("user/login", this.ruleForm)
              .then(() => {

                this.$router.push({path: this.redirect || "/"});
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {

            return false;
          }
        });
      }
    }
  };
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg: #283443;
  $light_gray: black;
  $cursor: black;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .register-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .register-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        -webkit-appearance: none;
        border-radius: 5px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }

    .el-form-item {
      /*border: 1px solid rgba(0, 0, 0, 0.3);*/
      /*background: transparent;*/
      /*border-radius: 5px;*/
      color: black;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: white;
  $dark_gray: #889aa4;
  $light_gray: #eee;
  $main_color: #134bde;

  .register-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .title {
      position: relative;
      width: 100%;
      background-color: #134bde;
      color: white;
      padding: 1rem 3rem;
      display: flex;
      height: 4rem;
      align-items: center;

      img {
        width: 6rem;
      }

      .sp2 {
        width: 1px;
        background-color: #f0f0f0;
        height: 63%;
        margin: 0 1rem;
      }

      .sp3 {
        font-size: 1.2rem;
        font-weight: bold;
      }
    }

    .conpane {
      margin: 0 auto;
      width: 750px;

      .minLH {
        line-height: 1.5rem;
      }

      .p1 {
        text-align: center;
        font-size: 1.6rem;
        font-weight: bold;
        margin: 4rem auto;
      }

      .p2 {
        width: 85%;
        border: 1px solid #dcdfe6;
        border-radius: 5px;
        display: flex;

        .sp1 {
          margin: 5px;
          width: 1px;
          background-color: #dcdfe6;
        }

        .sp2 {
          margin: auto;
        }

        .sp2-input {
          width: 75%;

          .cc {
            border: none;
          }
        }
      }

      .sp3-btn {
        width: calc(100% - 100px);
        height: 3rem;
        margin-top: 1rem;
      }

      .sp4 {
        position: relative;
        text-align: center;
        width: calc(100% - 100px);
      }
    }
  }
</style>

<style>
  .sp2-input input {
    border: none;
  }
</style>
